const baseUrl = 'https://tiyan.aly.xxnmkj.cn'
const imageUrl = 'https://tiyan.aly.xxnmkj.cn'
const platformid = '6278db142ed0a618712'; //平台ID-用于多平台开发时使用，默认可无效果
var project_key = 'wx01ece9d03d1238e6'; //项目密钥
var sign_rule = 1
var request = null;
const imgcdn = 0  //1为开启CDN图片状态 0为禁用CDN图片
const imgcdn_aly_handle = 0 //1为开启阿里云CDN图片处理 0为无需阿里云CDN图片处理
const wxgzh_appid = 'wxa9d9f2374d5bb5df' //微信公众号id
let channel = '' //用于渠道标识，主要应用于注册
// #ifdef APP-PLUS
if(plus.os.name == 'Android') {
	channel = '华为'
}
if(plus.os.name == 'iOS') {
	channel = '苹果'
}
// #endif
//测试token,userinfo
// uni.setStorageSync('token','496578fb-2df1-4f11-b6a9-e465cd4312f92')
// uni.removeStorageSync('token')
// uni.setStorageSync('userInfo',{
// 	id:1
// })


//cdn图片类型预定义
const img_type = () => {
	//存储方式 键-值对
	let img_types = {
		
	}
	return img_types
}

//定义缓存信息
const storage = () => {
	//存储方式 键-值对
	let storages = {
		token: 'token', //用户token，是
		userInfo: 'userInfo', //用户信息,是
		wxcode: 'wxcode', //微信code，是
		project_key: 'project_key', //项目密钥
	}
	return storages
}

//定义原生导航路径-要与pages.json同步
const native_navigation = [
	'/pages/tabbar/index/index',
	'/pages/tabbar/class/class',
	'/pages/tabbar/cartB/cart',
	'/pages/tabbar/my/my'
]

//请将所有接口请求，放于本段落下方

var getsign = () => {
	return ''
};
if (uni.getStorageSync('project_key')) {
	sign_rule = uni.getStorageSync('project_key').sign_rule
	getsign = () => {
		if (uni.getStorageSync('project_key').sign_rule == 1) {
			let md5 = require("@/api/md5.js")
			let timestampl = Date.parse(new Date());
			timestampl = timestampl / 1000;
			let sign = md5(md5(project_key) + timestampl) + timestampl
			return sign
		}
	}
}

const showTost = (msg) => {
	setTimeout(() => {
		uni.showToast({
			title: msg || '请求错误',
			icon: 'none',
			duration: 2000,
			mask: true,
		});
	}, 200)
};

var fnc = function() {
	console.log('fnc')
	return new Promise((resolve, reject) => {
		if (uni.getStorageSync('project_key')) {
			resolve()
		} else {
			uni.request({
				url: baseUrl + '/api/Xxnmapi/signconfig',
				header: {
					'content-type': 'application/x-www-form-urlencoded',
				},
				method: 'GET',
				success: (res) => {
					console.log('project_key', res.data.data)
					uni.setStorageSync('project_key', res.data.data)
					sign_rule = res.data.data.sign_rule
					resolve(res)
				},
				fail: (err) => {
					console.log(err)
					reject(err)
				}
			})
		}

	})
}



// 发起网络请求
request = (
	url,
	data = {},
	loading = true,
	method = 'post',
	callback = null
) => {
	console.log('request')

	return new Promise((resolve, reject) => {
		let makeRequest = async () => {
			await fnc()
			let token = uni.getStorageSync('token');
			getsign = () => {
				if (uni.getStorageSync('project_key').sign_rule == 1) {
					let md5 = require("@/api/md5.js")
					let timestampl = Date.parse(new Date());
					timestampl = timestampl / 1000;
					let sign = md5(md5(project_key) + timestampl) + timestampl
					return sign
				}
			}
			let sign = getsign();

			console.log('data', {
				'url': baseUrl + url,
				'data': data,
				'token': token,
				'sign': sign,
			})

			loading && uni.showLoading();
			uni.request({
				url: baseUrl + url,
				data: data,
				header: {
					'content-type': 'application/x-www-form-urlencoded',
					'token': token || '',
					'sign': sign,
					'platformid': platformid,
				},
				method: method,
				dataType: 'json',
				success: (response) => {
					if (loading) {
						uni.hideLoading();
					}
					console.log('response', response)
					if (response.statusCode == 200) {
						let result = response.data || null;
						if (result && result.code == 1) {
							resolve(result.data || {});
						} else if (result.code == 401) {
							//未登录
							// #ifdef APP-PLUS
							if (uni.getStorageSync('token')) {
								uni.removeStorageSync('token')
							}
							if (uni.getStorageSync('userInfo')) {
								uni.removeStorageSync('userInfo')
							}
							uni.navigateTo({
								url: '/pages/plugin/login/login'
							})
							// #endif
							// #ifdef MP-WEIXIN
							uni.navigateTo({
								url: '/pages/plugin/appletsLogin/appletsLogin'
							})
							// #endif
							return;
						} else {
							if (result) {
								showTost(result.msg);
								//code不为1,401
								result.err_type = 0
								reject(result)
								return
							}
							showTost('调试中');
						}
					} else {
						//statusCode!=200
						reject({
							err_type: 1
						})
						console.log(baseUrl + url)
						showTost('服务器发生错误');

					}
				},
				fail: (err) => {
					if (loading) {
						uni.hideLoading();
					}
					console.log('error',err)
					err.err_type = 2
					reject(err);
				}
			});
		};
		makeRequest();
	});
};

//统一封装设缓存方法，可设置缓存有效时间
//value string 缓存的键名
//obj string|object|Array 缓存的数据
//expire int 缓存的有效秒数 0=永久有效
const setStorageSync = (value, obj, expire = 0)=>{
	let time
	if(expire != 0){
		//设置了缓存的有效期
		time = (new Date()).valueOf() + expire * 1000
	}else{
		time = 0
	}
	
	let data = {
		obj:obj,
		time: time
	}
	
	uni.setStorageSync(value,data)
	
	//记录所有包含有效期的缓存列表，方便统一处理过期缓存数据
	if(time > 0){
		let storage_list = getStorageSync('storage_list')
		if(storage_list){
			storage_list = JSON.parse(storage_list)
			
			if(storage_list.indexOf(value) == -1){
				storage_list.push(value)
				
				storage_list = JSON.stringify(storage_list)
				uni.setStorageSync('storage_list',{obj:storage_list,time:0})
			}
		}else{
			storage_list = []
			storage_list.push(value)
			
			storage_list = JSON.stringify(storage_list)
			uni.setStorageSync('storage_list',{obj:storage_list,time:0})
		}
	}
}

//统一封装取缓存方法，如过期返回false
const getStorageSync = (value)=>{
	let data = uni.getStorageSync(value)
	if(!data){
		return false
	}
	
	if(data.time != 0){
		//存在缓存时间
		//取当前时间比较过期时间
		let time = (new Date()).valueOf()
		if(time-data.time > 0){
			//缓存已过期 清除该缓存
			let storage_list = JSON.parse(getStorageSync('storage_list')) 
			storage_list.splice(storage_list.indexOf(value),1)
			uni.removeStorageSync(value)
			
			if(storage_list.length > 0){
				storage_list = JSON.stringify(storage_list)
				uni.setStorageSync('storage_list',{obj:storage_list,time:0})
			}else{
				uni.removeStorageSync('storage_list')
			}
			return false
		}
	}
	
	//缓存存在并有效则返回数据
	return data.obj
}

//统一封装清理过期缓存
const clearExpireStorageSync = ()=>{
	//获取所有缓存列表
	let storage_list = getStorageSync('storage_list')
	if(storage_list){
		storage_list = JSON.parse(storage_list)
	
		for(let i = storage_list.length-1; i>-1; i--){
			getStorageSync(storage_list[i])
		}
	}
}

export {
	platformid,//平台id
	request,
	imageUrl,
	baseUrl,
	project_key,
	getsign,
	storage,
	native_navigation,
	setStorageSync, //统一封装设缓存方法，可设置缓存有效时间
	getStorageSync, //统一封装取缓存方法，如过期返回false
	clearExpireStorageSync, //统一封装清理过期缓存
	// #ifdef APP-PLUS
	channel,//app安装渠道
	// #endif
	
	//OSS配置开始
	imgcdn,//1为开启CDN图片状态 0为禁用CDN图片
	img_type,//cdn图片类型预定义
	imgcdn_aly_handle,//1为开启阿里云CDN图片处理 0为无需阿里云CDN图片处理
	//OSS配置结束
};
